<?php

namespace App\Exceptions;

use App\Pojo\Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Support\Facades\Log;

/**
 * 全局异常处理
 */
class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        // 处理所有异常
        $this->renderable(function (Throwable $e) {
            // 处理业务异常
            if ($e instanceof BusinessException) {
                return Response::error(
                    $e->getMessage(),
                    $e->getCode(),
                    $e->getData()
                );
            }

            // 处理其他异常
            if ($e instanceof \Illuminate\Validation\ValidationException) {
                return Response::error($e->getMessage(), 422, $e->errors());
            }

            if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
                return Response::notFound('资源未找到');
            }

            if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
                return Response::notFound('路由未找到');
            }

            if ($e instanceof \Illuminate\Auth\AuthenticationException) {
                // return Response::error('未授权', 401);
                // 打回登录页
                return redirect('/user/login');
            }

            if ($e instanceof \Predis\Connection\ConnectionException || 
                $e instanceof \RedisException) {
                return Response::error('Redis连接异常，请稍后重试', 500);
            }

            if ($e instanceof \Illuminate\Http\Client\ConnectionException || 
                $e instanceof \GuzzleHttp\Exception\ConnectException ||
                $e instanceof \GuzzleHttp\Exception\RequestException) {
                return Response::error('请求超时，请稍后重试', 504);
            }

            // 默认错误响应
            return Response::error(
                $e->getMessage(),
                method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500
            );
        });
    }
}
